import {
  plainToClass,
  plainToInstance,
  instanceToPlain,
} from 'class-transformer';
import { Body, Controller, Post, Req } from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';

import { ProfileService } from './profile.service';
import { ProfileCreateDto } from './profile.schema';
import { UserService } from '../user/user.service';
import { Profile } from '../../entity/profile.entity';
import { Response } from '../../../infra/schema/response';

@ApiTags('用户信息')
@Controller('profiles')
export class ProfileController {
  constructor(
    private readonly profileService: ProfileService,
    private readonly userService: UserService,
  ) {}

  @Post('action')
  @ApiBearerAuth()
  @ApiOperation({ summary: '操作用户信息', description: '创建/更新用户信息' })
  @ApiResponse({ type: Response<string> })
  async actionProfile(
    @Req() req: any,
    @Body() profileCreateDto: ProfileCreateDto,
  ) {
    const userId = req.user.id;
    const user = await this.userService.getUserById(userId);
    if (!user) {
      return Response.error('用户不存在');
    }

    const userProfile = await this.profileService.getProfileByUserId(userId);
    if (!userProfile) {
      const saveProfile = plainToClass(Profile, profileCreateDto);
      saveProfile.user = user;

      await this.profileService.saveProfile(saveProfile);
      return this.getResponse(saveProfile);
    }

    const createProfile = plainToInstance(Profile, profileCreateDto, {
      exposeUnsetFields: true,
    });
    createProfile.user = user;
    createProfile.id = userProfile.id;

    await this.profileService.updateProfile(createProfile);
    return this.getResponse(createProfile);
  }

  private getResponse(profile: Profile, excludePrefixes: string[] = ['user']) {
    const response = instanceToPlain(profile, {
      excludePrefixes: excludePrefixes,
    });
    return Response.success(response);
  }
}
